#!/usr/bin/env bash
# Fetch install: https://cmake.org/files/v3.11/cmake-3.11.1-Linux-x86_64.tar.gz
function download() {
  local url="${1}"
  local path="${2}"
  curl -f --progress-bar -L --output "${path}" "${url}"
}

readonly CMAKE_REMOTE_VERSION="https://gitee.com/oscstudio/git-dist/raw/master/version"

Xdirname=$(dirname "$0")
PrefixDir=$(
  cd "$Xdirname"
  pwd
) || exit 1

if [[ -f "${PrefixDir}/version" ]]; then
  # shellcheck source=/dev/null
  source "${PrefixDir}/version"
else
  echo "fetch remote version"
  curl -f --progress-bar -L --output /tmp/cmake-version "$CMAKE_REMOTE_VERSION"
  if [[ ! -f "/tmp/cmake-version" ]]; then
    echo -e "\\x1b[31munable download cmake version file\\x1b[0m"
    exit 1
  fi
  # shellcheck source=/dev/null
  source "/tmp/cmake-version"
fi

echo "download cmake: $CMAKE_VERSION.$CMAKE_PATCH"
CMAKE_BASENAME="cmake-${CMAKE_VERSION}.${CMAKE_PATCH}-Linux-x86_64"
CMAKE_NAME="${CMAKE_BASENAME}.tar.gz"
# https://github.com/Kitware/CMake/releases/download/v3.13.0/cmake-3.13.0-Linux-x86_64.tar.gz
CMAKE_URL="https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}.${CMAKE_PATCH}/${CMAKE_NAME}"
CMAKE_DOWNLOAD="/tmp/${CMAKE_NAME}"
download "${CMAKE_URL}" "${CMAKE_DOWNLOAD}"
cd /tmp || exit 1
tar -xvf "$CMAKE_NAME"

if [[ -d "/usr/local/cmake" ]]; then
  #statements
  rm "/usr/local/cmake" -rf
else
  mkdir -p "/usr/local"
fi

mv "/tmp/${CMAKE_BASENAME}" "/usr/local/cmake"

sudo ln -s -f "/usr/local/cmake/bin/cmake" "/usr/local/bin"
sudo ln -s -f "/usr/local/cmake/bin/ccmake" "/usr/local/bin"
sudo ln -s -f "/usr/local/cmake/bin/cpack" "/usr/local/bin"
